package com.xmkj.jijidriver;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.carbean.IsJieDanBean;
import com.common.carbean.XiCheListBean;
import com.common.cons.Constans;
import com.common.jiji.entity.BaseJJBean;
import com.common.jiji.entity.JJOrderListBean;
import com.common.jiji.entity.LoginBean;
import com.common.jiji.methods.JJOrderListMethods;
import com.common.jiji.methods.JieDanOrNotMethods;
import com.common.jiji.methods.LoginMethods;
import com.common.jiji.parms.JiedanParms;
import com.common.jiji.parms.LoginParms;
import com.common.jiji.parms.OrderParms;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.DataCenter;
import com.common.retrofit.entity.bean.UserDetailsBean;
import com.common.retrofit.methods.QueryIsJieDanMethods;
import com.common.retrofit.methods.UserInfoMethods;
import com.common.retrofit.methods.XiCheJieDanListMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.LogUtils;
import com.common.utils.MD5Utils;
import com.common.utils.SPUtils;
import com.common.utils.SizeUtils;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.recyclerview.refresh.adapter.CommonAdapter;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.xmkj.jijidriver.activity.OrderFrameActivity;
import com.xmkj.jijidriver.count.LoginActivtiy;
import com.xmkj.jijidriver.mine.activity.InfoCompileActivity;
import com.xmkj.jijidriver.order.OrderDetailActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import rx.functions.Action1;

/**
 * Created by chen on 2018/4/7.
 */

public class MainBizActivity extends BaseMvpActivity {
    @BindView(R.id.iv_menu)
    ImageView mIvMenu;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.ll_click_jiedan)
    LinearLayout mLlClickJiedan;
    @BindView(R.id.tv_state)
    TextView mTvState;
    boolean isOpen = false ;
    private List<JJOrderListBean.ResultBean> bean = new ArrayList<>();
    OrderAdapter adapter;
    private RelativeLayout rl_info;
    private RelativeLayout rl_order;
    private JJOrderListBean.ResultBean itemBean;
    private int currentPosition;
    private IsJieDanBean isJieDanBean;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_biz;
    }

    @Override
    protected void onViewCreated() {

    }

    @Override
    protected void doLogicFunc() {
        attachClickListener(mTvState);

        //洗车人查询是否接单
        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(DataCenter.TOKEN))) {
//            getUserInfo();

            gotoHttp();
            setRecyclerView();
        }
//        mPageSize = 12;

        attachClickListener(mIvMenu);
        attachClickListener(rl_info);
        attachClickListener(rl_order);

        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.ORDER_STATUS_CHANGE) && (Boolean) rxKeyEvent.getValue()) {
                    mPageIndex = 1;
                    gotoHttp();
                }
            }
        }));
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.ORDER_STATUS_CHANGE_OPEN)) {
                    int orderId = (int) rxKeyEvent.getValue();
                    Intent intent = new Intent(context, OrderFrameActivity.class);
                    intent.putExtra(OrderFrameActivity.ORDERID, orderId);
                    startActivity(intent);
                }
            }
        }));
    }



    private void queryIsJieDan(String detailid) {
        CommonSubscriber<IsJieDanBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                isJieDanBean = (IsJieDanBean) o;
                if (isJieDanBean.online == 1) {  // 不接单 状态
                    mTvState.setText("接单");
                    mLlClickJiedan.setVisibility(View.VISIBLE);
                    recyclerview.setVisibility(View.GONE);
                } else if (isJieDanBean.online == 2) {  // 接单中状态
                    mTvState.setText("停止接单");
                    mLlClickJiedan.setVisibility(View.GONE);
                    recyclerview.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        String detail_id = EmptyUtils.isEmpty(SPUtils.getShareString(Constans.DETAILS_ID)) ? detailid : SPUtils.getShareString(Constans.DETAILS_ID);
        QueryIsJieDanMethods.getInstance().onlineInfo(subscriber, uid, hashid, detail_id);
        rxManager.add(subscriber);
    }

    private PopupWindow popupWindow;

    @Override
    protected void onViewClicked(View view) {
        if (EmptyUtils.isEmpty(SPUtils.getShareString(DataCenter.TOKEN))) {
            gotoActivity(LoginActivtiy.class);
            return;
        }
        if (view.getId() == mIvMenu.getId()) {
            if (popupWindow == null) {
                // 创建PopupWindow
                View contentView = createContentView();    // 指定PopupWindow要显示的内容
                int width = 480;    // 指定PopupWindow的宽
                int height = 350;            // 指定PopupWindow的高
                boolean focusable = true;    // 指定PopupWindow是否可以获取焦点
                popupWindow = new PopupWindow(contentView, width, height, focusable);
                popupWindow.setBackgroundDrawable(new ColorDrawable());
            }

            // 显示PopupWindow
            View anchor = mIvMenu;    // 指定PopupWindow显示到et_number的下方
            int xoff = -150;    // 指定PopupWindow x方向的偏移量
            int yoff = 10;    // 指定PopupWindow y方向的偏移量
            popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int i = popupWindow.getContentView().getMeasuredWidth();
            popupWindow.showAsDropDown(anchor, -10 - i, 14);
        } else if (rl_info != null && rl_info.getId() == view.getId()) {
            gotoActivity(InfoCompileActivity.class);
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        } else if (rl_order != null && rl_order.getId() == view.getId()) {
            gotoActivity(OrderDetailActivity.class);
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        } else if (view.getId() == mTvState.getId()) {

            gotoJieDanOrNot();


        }
    }

    private void gotoJieDanOrNot() {

        showProgressingDialog();
        CommonSubscriber<BaseJJBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();

                if(isOpen){  // 是接单页面
                    isOpen = false;
                    mTvState.setText("接单");
                    mLlClickJiedan.setVisibility(View.VISIBLE);
                    recyclerview.setVisibility(View.GONE);
                }else {
                    isOpen = true;
                    mTvState.setText("停止接单");
                    mLlClickJiedan.setVisibility(View.GONE);
                    recyclerview.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        JiedanParms loginParms = new JiedanParms();
        loginParms.isOpen = isOpen?2:1;
        JieDanOrNotMethods.getInstance().openOrCloseOrder(subscriber, loginParms);
        rxManager.add(subscriber);
    }

    private View createContentView() {
        View view = View.inflate(context, R.layout.filter_popwindow, null);
//        ll_reward_rank = (LinearLayout) view.findViewById(R.id.ll_reward_rank);
//        ll_anchor_rank = (LinearLayout) view.findViewById(R.id.ll_anchor_rank);
        initPopWindowEnent(view);
        return view;


    }

    private void initPopWindowEnent(View view) {
        rl_info = view.findViewById(R.id.rl_info);
        rl_order = view.findViewById(R.id.rl_order);
        attachClickListener(rl_info);
        attachClickListener(rl_order);
//        ll_reward_rank.setOnClickListener(
    }

    private void gotoHttp() {
        if (EmptyUtils.isEmpty(SPUtils.getShareString(DataCenter.TOKEN))) {
            return;
        }
        CommonSubscriber<JJOrderListBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                JJOrderListBean beans = (JJOrderListBean) o;

                List<JJOrderListBean.ResultBean> beanList = beans.result;
                recyclerview.loadMoreComplete();
                // 下拉刷新
                if (mIsRefreshOrLoadMore == 0) {
                    recyclerview.refreshComplete();
                    adapter.clear();
                }

                if (EmptyUtils.isNotEmpty(beanList)) {
                    bean = beanList;
                    adapter.addAll(bean);
                } else if (mIsRefreshOrLoadMore == 0) {
//                    statusEmpty();
                    return;
                }

                if (EmptyUtils.isEmpty(beanList)) {
                    recyclerview.setNoMore(true);
                } else {
                    mIsHasNoData = beanList.size() < mPageSize;
                    recyclerview.setNoMore(mIsHasNoData);
                }
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }
        });

        OrderParms orderParms = new OrderParms();
        orderParms.pageIndex = mPageIndex+"";
//        orderParms.pageIndex = "0";
        orderParms.pageSize = mPageSize+"";
//        orderParms.pageSize = "2";
        JJOrderListMethods.getInstance().getOrderListNow(subscriber,orderParms);
        rxManager.add(subscriber);
    }

    private void setRecyclerView() {
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setHasFixedSize(true);
        recyclerview.setRefreshing(false);
        adapter = new OrderAdapter(context, bean);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new CommonAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(CommonAdapter adapter, View view, int position) {
                itemBean = (JJOrderListBean.ResultBean) adapter.mData.get(position);
                if (view.getId() == R.id.rl_details) { // 进入详情
                    if (EmptyUtils.isNotEmpty(itemBean.orderId)) {
                        //进入详情页面
                        Intent intent = new Intent(context, OrderFrameActivity.class);
                        intent.putExtra(OrderFrameActivity.ORDERID, itemBean.orderId);
                        startActivity(intent);
                    }
                } else if (view.getId() == R.id.tv_number) {  // 拨打电话
                    currentPosition = position;
//                    gotoCall();
                    //申请权限
                    AndPermission.with(MainBizActivity.this)
                            .requestCode(105)
                            .permission(Manifest.permission.CALL_PHONE)
                            .rationale(mRationaleListener)
                            .send();
                } else if (view.getId() == R.id.tv_location) { // 导航
                   /* double mEndLng = Double.valueOf(itemBean.longitude);
                    double mEndLat = Double.valueOf(itemBean.latitude);
                    if (mEndLng != 0.0 && mEndLat != 0.0) {
                        //移动APP调起Android高德地图方式
                        Intent intent = new Intent("android.intent.action.VIEW",
                                android.net.Uri.parse("androidamap://navi?sourceApplication=税源地图&lat=" + mEndLat + "&lon=" + mEndLng + "&dev=0&style=2"));
                        intent.setPackage("com.autonavi.minimap");
                        if (isInstallByread("com.autonavi.minimap")) {
                            startActivity(intent); // 启动调用
                        } else {
                            startBaiduMap(mEndLat, mEndLng);
                        }
                    } else {
                        showToastMsg("终点坐标不明确，请确认");
                    }
*/
                }
            }
        });

        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 1;
                mIsRefreshOrLoadMore = 0;
                gotoHttp();
            }

            @Override
            public void onLoadMore() {
                if (mIsHasNoData) {
                    recyclerview.loadMoreComplete();
                    recyclerview.setNoMore(true);
                    return;
                }
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                gotoHttp();
            }
        });
    }

    //判断是否安装目标应用
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName)
                .exists();
    }

    //移动APP调起Android百度地图方式
    private void startBaiduMap(double mEndLat, double mEndLng) {
        Intent intent = null;
        try {
            intent = Intent.getIntent
                    ("intent://map/navi?location=" + mEndLat + "," + mEndLng +
                            "&type=TIME&src=thirdapp.navi.hndist.sydt#Intent;scheme=bdapp;" +
                            "package=com.baidu.BaiduMap;end");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (isInstallByread("com.baidu.BaiduMap")) {
            startActivity(intent); // 启动调用
        } else {
            showToastMsg("没有安装高德/百度地图客户端");
        }
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    //申请权限
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(MainBizActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能拨打电话，请把权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };

    @PermissionYes(105)
    private void openPic() {
        LogUtils.e("成功回调了-->");
        gotoCall();


    }

    private void gotoCall() {
        if (EmptyUtils.isEmpty(itemBean.phone)) {
            return;
        }
        showTwoDialog("提示", itemBean.phone, "拨打", "取消");
        setOnDialogViewClick(new OnDialogViewClick() {
            @Override
            public void leftViewClick() {
//                        showToastMsg("hha");
                Intent intent = new Intent(); // 意图对象：动作 + 数据
                intent.setAction(Intent.ACTION_CALL); // 设置动作
                Uri data = Uri.parse("tel:" + itemBean.phone); // 设置数据
                intent.setData(data);
                startActivity(intent); // 激活Activity组件
            }

            @Override
            public void singleViewClick() {

            }
        });


    }

    @PermissionNo(105)
    private void injectPic() {
        LogUtils.e("失败回调了-->");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

}
